package com.yksj.healthtalk.ui.app;

import java.util.Calendar;
import java.util.Collection;
import java.util.List;

import android.app.Activity;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.text.format.Time;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.MKGeneralListener;
import com.open.share.ContextMgr;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.entity.MessageEntity;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.HttpUrls;
import com.yksj.healthtalk.net.socket.SmartControlClient;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.CoreService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.chatting.ChatLatelyListActivity;
import com.yksj.healthtalk.ui.login.WelcomeActivity;
import com.yksj.healthtalk.utils.AppCashHandler;
import com.yksj.healthtalk.utils.DataParseUtil;
import com.yksj.healthtalk.utils.LogUtil;
import com.yksj.healthtalk.utils.SharePreUtils;

public class HTalkApplication extends Application {
	
	public static final String TAG = "HTalkApplication";
	public static final int NOTIFY_ID = 0x0;
//	public static final String strKey = "c0K7ypRRjn2MjhKRK8t6Cvsu";
	public static int haveShoppingCar = 0;
	
	private static HTalkApplication mApplication;
	private static Resources mResources;
	
	/**
	 * 系统所有http请求地址集合
	 */
	private static HttpUrls httpUrls;
	
	/**
	 * 全局数据
	 */
	private static AppData appData;
	
	private BMapManager mBMapManager = null;
	private NotificationManager mNotificationManager;
	private ConnectivityManager mConnectivityManager;
	 
	public void onCreate(){
		super.onCreate();
		
		mApplication = this;
		mResources = getResources();
		
		init();
	}
	private void init(){
		AppCashHandler appExceptionCashHandler = AppCashHandler.getInstance();
		appExceptionCashHandler.init(this);
		
		//上传异常日志
		if(isWifi()){
			appExceptionCashHandler.sendLogToServer();
		}
		
		initLocationManager(this);
		ContextMgr.setContext(this);//微博
		
		if(httpUrls == null)httpUrls = new HttpUrls(getString(R.string.web_root));
		if(appData == null )appData = new AppData();
		HttpRestClient.setmHttpUrls(httpUrls);
		
		//initGlobData();
	}
	
	public void showNotify(String content){
		/*//4.0及以后
		if(android.os.Build.VERSION.SDK_INT >= 14){
		}else*/
		Intent intent = new Intent(mApplication,ChatLatelyListActivity.class);
		intent.putExtra("notifi",true);
		Notification notification = new Notification(R.drawable.launcher_logo,content,System.currentTimeMillis());
		notification.contentView = null;
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
//		notification.flags |= Notification.DEFAULT_LIGHTS;
		SettingManager manager = SettingManager.getInstance();
		//需要服务提醒
		if(manager.isServiceNote()){
			final Calendar calendar = Calendar.getInstance();
			final int hour = calendar.get(Calendar.HOUR_OF_DAY);
//			Time time = new Time("GMT+8");
//			time.set(System.currentTimeMillis());
			if(hour > 6 && hour < 22){//提醒
				if(manager.isSoundOpen())notification.defaults |= Notification.DEFAULT_SOUND;
				if(manager.isVibrateOpen())notification.defaults |= Notification.DEFAULT_VIBRATE;
			}else{
				
			}
		}else{
			if(manager.isSoundOpen())notification.defaults |= Notification.DEFAULT_SOUND;
			if(manager.isVibrateOpen())notification.defaults |= Notification.DEFAULT_VIBRATE;
		}
//		notification.defaults |= Notification.DEFAULT_SOUND;
//		notification.defaults |= Notification.DEFAULT_VIBRATE;
		notification.setLatestEventInfo(mApplication, "壹健康", content,PendingIntent.getActivity(mApplication, 0,intent, 0));
		mNotificationManager.notify(HTalkApplication.NOTIFY_ID,notification);
	}
	
	public void cancelNotify(){
		mNotificationManager.cancel(HTalkApplication.NOTIFY_ID);
	}
	
	//用户条款和隐私协议
	public String getUserAgentPath(){
		return HttpRestClient.getmHttpUrls().WEB_ROOT+
				"/sms_web/UserAgreementServlet300?Type=queryAgreement&customerid="
				+SmartControlClient.getControlClient().getUserId()+
				"&agreementType=Registered&system_version="+
				getAppVersionName();
	}
	
	//用户条款和隐私协议
	public String getDoctorUserAgentPath(){
		return HttpRestClient.getmHttpUrls().WEB_ROOT+"/sms_web/UserAgreementServlet300?Type=queryAgreement&customerid="+SmartFoxClient.getLoginUserId()+"&agreementType=Registered&system_version="+
				getAppVersionName();
	}
	
	//医生注册条款和隐私协议
	public String getDoctorAgentPath(){
		return HttpRestClient.getmHttpUrls().WEB_ROOT+"/sms_web/UserAgreementServlet300?Type=queryAgreement&customerid="
				+SmartControlClient.getControlClient().getUserId()+
				"&agreementType=Doctor_Apply&system_version="+HTalkApplication.getAppVersionName();
	}
	
	//功能介绍
	public String getFunctionIntroduction(){
		return "http://www.h-tlk.com/JumpPage/Health_Introduce_410.html";
	}
	
	public synchronized NotificationManager getNotificationManager(){
		if(mNotificationManager == null){
			mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
		}
		return mNotificationManager;
	}
	
	public synchronized ConnectivityManager getConnectivityManager(){
		if(mConnectivityManager == null){
			mConnectivityManager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
		}
		return mConnectivityManager;
	}
	
	/**
	 * 获取版本号
	 * @return
	 */
	public static String getAppVersionName() {
		try {
			PackageInfo packageInfo = mApplication.getPackageManager()
					.getPackageInfo(mApplication.getPackageName(), 0);
			return packageInfo.versionName;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "4.1.0";
	}
	
	/**
	 * 获取指南版本号
	 * @return
	 */
	public static String getHelpAppVersionName() {
//		return "4.0.2";
		return getAppVersionName();
	}
	
	/**
	 * 获取版本号
	 * @return
	 */
	public static int getAppVersionCode() {
		try {
			PackageInfo packageInfo = mApplication.getPackageManager()
					.getPackageInfo(mApplication.getPackageName(), 0);
			return packageInfo.versionCode;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}
	
	/**
	 * 网络是否有效
	 * @return false ,true
	 */
	public synchronized boolean isNetWork(){
		getConnectivityManager();
		
		NetworkInfo info = mConnectivityManager.getActiveNetworkInfo();
		if (info == null) {
			return false;
		}
		return info.isConnected();
	}
	
	/**
	 * 是否是wifi网络
	 * @return
	 */
	public synchronized boolean isWifi(){
		getConnectivityManager();
		NetworkInfo info = mConnectivityManager.getActiveNetworkInfo();
		if (info == null) {
			return false;
		}
		return info.getType() == ConnectivityManager.TYPE_WIFI;
	}
	
	public static HTalkApplication getApplication(){
		return mApplication;
	}
	
	public static Resources getAppResources(){
		return mResources;
	}
	
	private void initLocationManager(Context context){
		if (mBMapManager == null) {
			mBMapManager = new BMapManager(this);
		}
		mBMapManager.init(new MKGeneralListener() {
			@Override
			public void onGetPermissionState(int arg0) {//授权问题
			}
			@Override
			public void onGetNetworkState(int arg0) {//您的网络出错啦
			}
		});
//		mBMapManager.init(strKey,null);
	}
	
	/**
	 * 登陆清除
	 */
	public static  void clearAll(){
		if(appData != null){
			appData.clearAll();
		}
	}
	
	/**
	 * 清楚全局数据
	 */
	public void destoryAll(){
		/*setAppData(null);
		setHttpUrls(null);
		setSettingManager(null);*/
	}
	
	public void setHttpUrls(HttpUrls httpUrls) {
		this.httpUrls = httpUrls;
	}

	/*public SettingManager getSettingManager() {
		return settingManager;
	}

	public void setSettingManager(SettingManager settingManager) {
		this.settingManager = settingManager;
	}*/

	public void setAppData(AppData appData) {
		this.appData = appData;
	}
	
	public static HTalkApplication getHTalkApplication(){
		return mApplication;
	}
	
	public static AppData getAppData(){
		return appData;
	}
	
	public static HttpUrls getHttpUrls(){
		return mApplication.httpUrls;
	}
	
	public static String getMd5UserId(){
		return SmartControlClient.getControlClient().getUserMd5Id();
	}
	
	/**
	 * 未读消息数量
	 * @return
	 */
	public static int getNoReadMesgSize(){
		Collection<List<MessageEntity>> lists = appData.messageCllection.values();
		int i = 0;
		for (List<MessageEntity> list : lists) {
			i += list.size();
		}
		return i;
	}
	
	/**
	 * 异常退出登录处理
	 */
	public static void onHandleCrashedLogin(Bundle bundle,Activity context){
		try{
			if(bundle != null && SmartControlClient.getControlClient().getInfoEntity() == null){
				String parame = SharePreUtils.getLoginUserInfo();
				String[] str = SharePreUtils.fatchUserLoginCache();
				JSONObject jsonObject = JSON.parseObject(parame);
				CustomerInfoEntity entity = DataParseUtil.jsonToCustomerInfo(jsonObject);
				SmartControlClient controlClient = SmartControlClient.getControlClient();
				controlClient.setUserPassword(str[0],str[1]);
				controlClient.setCustomerInfoEntity(entity);
				CoreService.actionLogin(context);
			}
		}catch(Exception e){
			SharePreUtils.updateLoginState(false);
			Intent intent = new Intent(context,WelcomeActivity.class);
			context.startActivity(intent);
			context.finish();
		}
	}
}